var http=require('http')
var fs=require('fs')
var path=require('path')

function createTime(ctimeMs){
    var date1=new Date(ctimeMs);
    var year=date1.getFullYear();
    var month=date1.getMonth()+1;
    var day=date1.getDate();
    return year+'-'+month+'-'+day
}


http.createServer((req,res)=>{
    var urlStr=req.url;
    var filePath=path.join(__dirname,'/index.html')
    var imgPath=path.join(__dirname,'/icon.png')
    var filesPath=path.join(__dirname,'/fileDir')
    var files=fs.readdirSync(filesPath)
    
    
    if(urlStr=='/'){
        var fileContent=fs.readFileSync(filePath)
        res.writeHead(200,{'Content-Type':'text/html;charset=utf-8'})
        res.write(fileContent)
        res.end()
    }
    else if(urlStr=='/icon.png'){
        var imgContent=fs.readFileSync(imgPath)
        res.writeHead(200,{'Content-Type':'image/png'})
        res.write(imgContent)
        res.end()
    }
    else if(urlStr=='/getlist'){
        var arr=[]
        for(var i=0;i<files.length;i++){
            var fileObj=fs.statSync(filesPath+'/'+files[i])
            if(fileObj.isFile()){
                var obj={}
                obj.fileType='file'
                obj.fileName='文本'
                obj.fileSize=fileObj.size
                obj.fileTime=createTime(fileObj.ctimeMs)
            }
            else if(fileObj.isDirectory()){
                var obj={}
                obj.fileType='folder'
                obj.fileName=files[i]
                obj.fileSize=fileObj.size
                obj.fileTime=createTime(fileObj.ctimeMs)
            }
            
            arr.push(obj)
        }
        var jsonStr=JSON.stringify(arr)
        res.writeHead(200,{'Content-Type':'text/plain'})
        res.write(jsonStr)
        res.end()
    }
}).listen(8081)